<template>
  <div>
    <!-- 表格内容 start  -->
    <Table
      ref="table"
      border
      :columns="tableColumns"
      :data="tableDataList"
      :loading="loading"
      height='500'
      class="ivu-mt"
      stripe
    >
      <template slot-scope="{ row, index }" slot="action">
        {{ actionRender({index, row}) }}
      </template>
    </Table>
    <!-- 表格内容 end  -->
    <!-- 分页 start  -->
    <div class="ivu-mt ivu-text-center">
      <Page
        :total="page.totalNum"
        show-total
        show-sizer
        transfer
        :current.sync="page.nowPage"
        @on-change="getData"
        @on-page-size-change="handleChangePageSize"
      />
    </div>
    <!-- 分页 end  -->
  </div>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { getBtnsId } from '@/libs/btnsPermission';
import { mapState, mapGetters, mapMutations } from 'vuex';
import { generateColumnsFn, renderActionFn } from '../configjs/baseTable';
import { createBtnsForTableAction } from '@/utils/tableActionUtils';
import { isResponseSuccess, isResponseSuccessState } from '@/utils/bizUtils'
import util from '@/libs/util';
import { isBeforeRecordDate } from '@/utils/salePrice'

export default {
  props: {
    dynamicData: {
      type: Object
    },
    pagePath: {
      type: String
    },
    orderState: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      util: util,
      basePath: this.dynamicData.basePath, // 拼接基础路径
      tableDataList: [],
      tableColumns: [],
      loading: false,
      page: {
        totalNum: 0,
        nowPage: 1,
        pageShow: 10
      }
    };
  },
  computed: {
    ...mapState('admin/baseList', [
      'listData',
      'searchFormData', // 列表页筛选条件
      'searchFormDataQ' // 列表页筛选条件查询类型
    ]),
    ...mapGetters('permissions/systemBtns', [
      'showBtn'
    ]),
  },
  watch: {
    orderState (n, o) {
      this.getData();
    }
  },
  created () {
    this.tableColumns = generateColumnsFn(this.actionRender);
  },
  methods: {
    ...mapMutations('admin/baseList', ['setTableRowData']),
    handleChangePageSize (val) {
      this.page.pageShow = val;
      this.getData();
    },
    // 获取表格的数据
    getData () {
      let searchParam = [];
      const [pushTime = '', pushTime2 = ''] = this.searchFormData?.pushTime ?? [];
      const searchData = {
        ...this.searchFormData,
        pushTime,
        pushTime2
      }
      const searchDataQ = {
        ...this.searchFormDataQ,
        pushTime_q: 'GE',
        pushTime2_q: 'LT',
      }
      Object.keys(searchData).forEach((key) => {
        searchParam.push({ name: key, value: searchData[key] });
      });
      Object.keys(searchDataQ).forEach((key) => {
        searchParam.push({ name: key, value: searchDataQ[key] });
      });
      let data = {
        nowPage: this.page.nowPage,
        pageShow: this.page.pageShow,
        searchParam: JSON.stringify(searchParam),
        sortName: '',
        sortType: ''
      };
      let curBtnId = getBtnsId('查询');
      sessionStorage.setItem('buttonId', curBtnId);
      this.loading = true;
      ApiRequest(
        '/sysback/product/update/getSpuByRecord/querySpuList',
        'post',
        data
      ).then(res => {
        this.loading = false;
        if (res.retStatus !== '1') { return false }
        this.tableDataList = res.retData.results.reduce((value, item) => {
          item.actions = createBtnsForTableAction({ showBtn: this.showBtn, data: item });
          value.push(item);
          return value;
        }, []);
        this.page.totalNum = res.retData.totalNum;
      })
    },
    actionRender (h, { index, row }) {
      return (
        <div class="table-action">
          {
            renderActionFn(h, {
              list: row.actions,
              methods: this.toDifferentPageFn,
              row
            })
          }
        </div>
      )
    },
    /* action操作栏跳转页面方法 */
    toDifferentPageFn (data) {
      let { item, row } = data;
      let pageType = item.name;
      let workflowRequestId = row.workflowRequestId;
      switch (pageType) {
        case 'Audit':
          /*
            只有以下五个单据审核不进OA页面
            { commitType: basicInfo - commitTypeStr: 基本信息 }
            { commitType: supplyGoods - commitTypeStr: 供货信息 }
            { commitType: acceptance - commitTypeStr: 验收信息 }
            { commitType: acceptanceCollect - commitTypeStr: 验收标准（临采） }
          */
          let notEnterOaList = [
            'basicInfo', 'supplyGoods', 'acceptanceCollect'
          ];
          let notEnterOaFlag = _.includes(notEnterOaList, row.commitType) // 是否不进OA页面标识 - true：不进  false：进
          notEnterOaFlag ? this.skipAuditPageFn(row) : this.skipOaPageAction(workflowRequestId);
          break;
        case 'AuditRecord':
          this.skipOaPageAction(workflowRequestId);
          break;
        case 'Chage':
          this.skipEditPageFn(row);
          break;
        case 'View':
          this.skipViewPageFn(row);
          break;
        case 'Delete':
          this.handleDelete(row);
          break;
        case 'PackUp':
          this.handlePackUp(row)
      }
    },
    /* 跳转修改页面 */
    skipEditPageFn (row) {
      switch (row.commitType) {
        /* 架构信息 */
        case 'structureInfo':
          this.$router.push({
            name: 'chageFromManageAddEdit',
            query: { recordNo: row.recordNo, uuid: row.uuid, type: 'edit' },
          });
          break;
        /* 基本信息 */
        case 'basicInfoNew':
          this.$router.push({
            name: 'modifyBasicInfoEdit',
            query: { recordNo: row.recordNo },
          });
          break;
        /* 基本信息 - 历史 */
        case 'basicInfo':
          this.$router.push({
            name: 'chageFromManageBaseEdit',
            query: { recordNo: row.recordNo, uuid: row.uuid, type: 'edit' },
          });
          break;
        /* 管理信息 */
        case 'allManaging':
          this.$router.push({
            name: 'chageFromManageInfoEdit',
            query: { recordNo: row.recordNo, uuid: row.uuid, type: 'edit' },
          });
          break;
        /* SKU信息 */
        case 'package':
          this.$router.push({
            name: 'chageFromManageSKUEdit',
            query: { recordNo: row.recordNo, uuid: row.uuid, type: 'edit' },
          });
          break;
        /* 图文信息 */
        case 'pic':
          this.$router.push({
            path: '/commodity/commodityInfoUpdate/chageFromManage/chageFromManageImageText',
            query: { recordNo: row.recordNo, productUuid: row.uuid },
          });
          break;
        /* 供货信息 */
        case 'supplyGoods':
          this.$router.push({
            path: '/commodity/commodityInfoUpdate/chageFromManage/chageFromManageSupplyInfo',
            query: { recordNo: row.recordNo, uuid: row.uuid },
          });
          break;
        /* 进价信息 */
        case 'supplyPrice':
          this.$router.push({
            path: '/commodity/commodityInfoUpdate/chageFromManage/chageFromManageenterPrice',
            query: { recordNo: row.recordNo, uuid: row.uuid },
          });
          break;
        /* 进价信息-多计量 */
        case 'supplySteelPrice':
          this.$router.push({
            path: '/commodity/commodityInfoUpdate/chageFromManage/chageFromManageenterPriceSteel',
            query: { recordNo: row.recordNo, uuid: row.uuid },
          });
          break;
        /* 售价信息 */
        case 'salePrice':
          this.$router.push({
            name: 'editSalePriceRecordEdit',
            query: { recordNo: row.recordNo, uuid: row.uuid },
          });
          break;
        /* 验收标准 */
        case 'acceptance':
          this.$router.push({
            path: '/commodity/acceptanceCriteria/acceptanceCriteriaManage/acceptanceCriteriaManagebatchEditY',
            query: { recordNo: row.recordNo, uuids: row.uuid }
          })
          break;
        /* 验收标准（临采） */
        case 'acceptanceCollect':
          this.$router.push({
            path: '/commodity/acceptanceCriteria/acceptanceCriteriaManage/acceptanceCriteriaManagebatchEditY',
            query: { recordNo: row.recordNo, uuids: row.uuid }
          })
          break;
        /* 多供进价 */
        case 'supplyMorePrice':
          this.$router.push({
            name: 'chageFromManageMuchSupplyEdit',
            query: { recordNo: row.recordNo },
          });
          break;
        /* 多供进价-多计量 */
        case 'supplyMoreSteelPrice':
          this.$router.push({
            name: 'chageFromManageMuchSupplySteelEdit',
            query: { recordNo: row.recordNo },
          });
          break;
        /* 修改品类 */
        case 'modifySpuCategory':
          this.$router.push({
            name: 'categoryEditRecordModify',
            query: { recordNo: row.recordNo }
          });
          break;
        /* 修改SKU规格 */
        case 'editSkuSpec':
          this.$router.push({
            name: 'skuSpecEditHome',
            query: { recordNo: row.recordNo }
          });
          break;
        /* 修改到货周期 */
        case 'arrivalCycle':
          this.$router.push({
            name: 'batchModifyArrivalTime',
            query: { recordNo: row.recordNo }
          });
      }
    },
    // 表格删除
    handleDelete (row) {
      this.deleteCommonRecord(row);
    },
    // 删除通用单据
    deleteCommonRecord (row) {
      this.postRequestRecord({
        url: `/sysback/product/update/record/deleteRecordByNo?recordNo=${row.recordNo}`,
        type: 'post'
      }).then(retData => {
        if (retData) {
          this.$message.success(retData)
          this.getData();
        }
      });
    },
    // 取回
    handlePackUp (row) {
      this.packUpCommonRecord(row);
    },
    // 取回单据
    async packUpCommonRecord (row) {
      try {
        this.loading = true;
        const res = await ApiRequest(
          '/sysback/oa/getBackWorkflow',
          'post',
          { recordNo: row.recordNo, oaRequestId: row.workflowRequestId }
        );
        this.loading = false;
        if (isResponseSuccessState(res.retStatus)) {
          this.$message.success('取回成功');
          this.getData();
        }
      } catch (err) {
        this.loading = false;
      }
    },
    // 单据post请求
    async postRequestRecord ({ url, type, data = {}, isFormData = false }) {
      try {
        this.loading = true;
        const res = await ApiRequest(url, type, data, isFormData);
        this.loading = false;
        if (isResponseSuccess(res)) {
          return res.retData;
        }
      } catch (err) {
        this.loading = false;
      }
    },
    /* 跳转查看页面 */
    skipViewPageFn (row) {
      switch (row.commitType) {
        /* 架构信息 */
        case 'structureInfo':
          this.openNewWindowPageFn({
            name: 'chageFromManageAddView',
            query: { recordNo: row.recordNo, uuid: row.uuid, type: 'view' },
          });
          break;
        /* 基本信息 */
        case 'basicInfoNew':
          this.openNewWindowPageFn({
            name: 'modifyBasicInfoView',
            query: { recordNo: row.recordNo },
          });
          break;
        /* 基本信息 - 历史 */
        case 'basicInfo':
          this.openNewWindowPageFn({
            name: 'chageFromManageBaseView',
            query: { recordNo: row.recordNo, uuid: row.uuid, type: 'view' },
          });
          break;
        /* 管理信息 */
        case 'allManaging':
          this.openNewWindowPageFn({
            name: 'chageFromManageInfoView',
            query: { recordNo: row.recordNo, uuid: row.uuid, type: 'view' },
          });
          break;
        /* SKU信息 */
        case 'package':
          this.openNewWindowPageFn({
            name: 'chageFromManageSKUView',
            query: { recordNo: row.recordNo, uuid: row.uuid, type: 'view' },
          });
          break;
        /* 供货信息 */
        case 'supplyGoods':
          this.openNewWindowPageFn({
            path: '/commodity/commodityInfoUpdate/chageFromManage/gonghuoView',
            query: { recordNo: row.recordNo, uuid: row.uuid },
          });
          break;
        /* 供货信息-停供(删除) */
        case 'supplyGoodsStop':
          this.openNewWindowPageFn({
            name: 'stopSupplyInfoView',
            query: { recordNo: row.recordNo },
          });
          break;
        /* 供货信息-恢复供货 */
        case 'supplyGoodsRecover':
          this.openNewWindowPageFn({
            name: 'recoverSupplyInfoView',
            query: { recordNo: row.recordNo },
          });
          break;
        /* 进价信息 */
        case 'supplyPrice':
          this.openNewWindowPageFn({
            path: '/commodity/commodityInfoUpdate/chageFromManage/jinjiaView',
            query: { recordNo: row.recordNo, uuid: row.uuid },
          });
          break;
        /* 进价信息-多计量 */
        case 'supplySteelPrice':
          this.openNewWindowPageFn({
            path: '/commodity/commodityInfoUpdate/chageFromManage/jinjiaViewSteel',
            query: { recordNo: row.recordNo, uuid: row.uuid },
          });
          break;
        /* 售价信息 */
        case 'salePrice':
          const isBefore = isBeforeRecordDate(row.recordNo)
          const routerName = isBefore ? 'sellPriceView' : 'editSalePriceRecordView'
          this.openNewWindowPageFn({
            name: routerName,
            query: { recordNo: row.recordNo, uuid: row.uuid },
          });
          break;
        /* 售价信息-多计量 （无需判断时间节点，新售价没有多计量） */
        case 'saleSteelPrice':
          this.openNewWindowPageFn({
            path: '/commodity/commodityInfoUpdate/chageFromManage/chageFromManageSellPriceSteelView',
            query: { recordNo: row.recordNo, uuid: row.uuid },
          });
          break;
        /* 售价价格组 */
        case 'saleGroup':
          this.openNewWindowPageFn({
            path: '/commodity/commodityInfoUpdate/chageFromManage/shoujiaGroupView',
            query: { recordNo: row.recordNo, uuid: row.uuid },
          });
          break;
        /* 验收标准 */
        case 'acceptance':
          this.openNewWindowPageFn({
            // path: '/commodity/commodityInfoUpdate/acceptanceCriteriaManage/acceptanceCriteriaManageViewY',
            name: 'batchEditAcceptanceView',
            query: { recordNo: row.recordNo }
          });
          break;
        /* 验收标准（临采） */
        case 'acceptanceCollect':
          this.openNewWindowPageFn({
            path: '/commodity/commodityInfoUpdate/acceptanceCriteriaManage/acceptanceCriteriaManageViewY',
            query: { recordNo: row.recordNo }
          });
          break;
        /* 潜在商品验收标准 */
        case 'potentialAcceptance':
          this.$router.push({
            name: 'acceptanceRecordView',
            query: { recordNo: row.recordNo }
          })
          break;
        /* 售价类型-单计量 */
        case 'saleType':
          this.openNewWindowPageFn({
            path: '/commodity/commodityInfoUpdate/chageFromManage/chageFromManageSellPriceTypeView',
            query: { recordNo: row.recordNo },
          });
          break;
        /* 售价类型-多计量 */
        case 'saleSteelType':
          this.openNewWindowPageFn({
            path: '/commodity/commodityInfoUpdate/chageFromManage/chageFromManageSellPriceTypeView',
            query: { recordNo: row.recordNo },
          });
          break;
        /* 修改主供应商 */
        case 'supplyGoodsMainSupply':
          this.openNewWindowPageFn({
            path: '/commodity/commodityInfoUpdate/chageFromManage/maintainView',
            query: { recordNo: row.recordNo, uuid: row.uuid },
          });
          break;
        // 新增销售区域
        case 'addSupplySaleArea':
          this.openNewWindowPageFn({
            name: 'addSaleAreaRecordView',
            query: { recordNo: row.recordNo }
          })
          break
        // 删除销售区域
        case 'deleteSupplySaleArea':
          this.openNewWindowPageFn({
            name: 'deleteSaleAreaRecordView',
            query: { recordNo: row.recordNo }
          })
          break
        // 批量修改销售区域
        case 'alignmentSupplySaleArea':
          this.openNewWindowPageFn({
            name: 'saleAreaAlignRecordView',
            query: { recordNo: row.recordNo }
          })
          break
        // 销售区域（历史）
        case 'supplySaleArea':
          this.openNewWindowPageFn({
            name: 'commodityInfoModifySalesAreaDetail',
            query: { uuid: row.uuid }
          })
          break
        /* 参照城市 */
        case 'supplyPriceAndRefCity':
          this.openNewWindowPageFn({
            name: 'chageFromManageTemplateCityView',
            query: {
              recordNo: row.recordNo,
            }, // 查看修改参照城市进价信息
          });
          break;
        /* 参照城市多计量 */
        case 'supplySteelPriceAndRefCity':
          this.openNewWindowPageFn({
            name: 'chageFromManageTemplateCitySteelView',
            query: {
              recordNo: row.recordNo,
            }, // 查看修改参照城市进价信息(多计量)
          });
          break;
        /* 多供进价信息-单计量 */
        case 'supplyMorePrice':
          this.openNewWindowPageFn({
            path: '/commodity/commodityInfoUpdate/chageFromManage/chageFromManageMuchSupplyView',
            query: {
              recordNo: row.recordNo,
              uuid: row.uuid,
              name: '多供进价',
              type: '单计量',
            },
          });
          break;
        /* 多供进价信息-多计量 */
        case 'supplyMoreSteelPrice':
          this.openNewWindowPageFn({
            path: '/commodity/commodityInfoUpdate/chageFromManage/chageFromManageMuchSupplyView',
            query: {
              recordNo: row.recordNo,
              uuid: row.uuid,
              name: '多供进价',
              type: '多计量',
            },
          });
          break;
        /* 验收标准-批量新增查看 */
        case 'addedAcceptance':
          this.openNewWindowPageFn({
            name: 'batchAddAcceptanceView',
            query: { recordNo: row.recordNo, },
          });
          break;
        /* 验收标准-批量修改查看 */
        case 'editAcceptance':
          this.openNewWindowPageFn({
            name: 'batchEditAcceptanceView',
            query: { recordNo: row.recordNo, },
          });
          break;
        /* 修改品类查看 */
        case 'modifySpuCategory':
          this.openNewWindowPageFn({
            name: 'categoryEditRecordView',
            query: { recordNo: row.recordNo }
          });
          break;
        /* 修改到货周期 */
        case 'arrivalCycle':
          this.openNewWindowPageFn({
            name: 'batchModifyArrivalTimeView',
            query: { recordNo: row.recordNo }
          });
          break;
        /* SKU计量单位-多计量 */
        case 'multiSkuUnit':
          this.openNewWindowPageFn({
            name: 'unitsManageView',
            query: { recordNo: row.recordNo }
          });
          break;
        /* 修改SKU规格 */
        case 'editSkuSpec':
          this.openNewWindowPageFn({
            name: 'skuSpecEditRecordView',
            query: { recordNo: row.recordNo }
          });
          break;
        // 区域商品起售量-编辑
        case 'skuAreaSaleMin':
          this.openNewWindowPageFn({
            name: 'areaStartingSalesQuantityRecordView',
            query: { recordNo: row.recordNo }
          });
          break;
        // 区域商品起售量-删除
        case 'skuAreaSaleMinDel':
          this.openNewWindowPageFn({
            name: 'areaStartingSalesQuantityRecordView',
            query: { recordNo: row.recordNo }
          });
          break;
      }
    },
    /* 跳转审核页面 */
    skipAuditPageFn (row) {
      switch (row.commitType) {
        case 'basicInfo':
          this.openNewWindowPageFn({
            name: 'chageFromManageBaseView',
            query: { recordNo: row.recordNo, uuid: row.uuid, type: 'audit' },
          });
          break;
        case 'package':
          this.openNewWindowPageFn({
            name: 'chageFromManageSKUView',
            query: { recordNo: row.recordNo, uuid: row.uuid, type: 'audit' },
          });
          break;
        case 'supplyGoods':
          this.openNewWindowPageFn({
            path: '/commodity/commodityInfoUpdate/chageFromManage/gonghuoView',
            query: { recordNo: row.recordNo, uuid: row.uuid, type: 'audit' },
          });
          break;
        /* case 'acceptance':
          this.openNewWindowPageFn({
            name: 'batchEditAcceptanceView',
            query: { recordNo: row.recordNo, type: 'audit' },
          });
          break; */
        case 'acceptanceCollect':
          this.openNewWindowPageFn({
            path: '/commodity/commodityInfoUpdate/acceptanceCriteriaManage/acceptanceCriteriaManageViewY',
            query: { recordNo: row.recordNo, type: 'audit' },
          });
          break;
        /* case 'addedAcceptance':
          this.openNewWindowPageFn({
            name: 'batchAddAcceptanceView',
            query: { recordNo: row.recordNo, type: 'audit' },
          });
          break; */
      }
    },
    /* 跳转OA */
    skipOaPageAction (workflowRequestId) {
      this.loading = true;
      // 跳转审批界面
      ApiRequest(`/sysback/oa/getAuditPageUrl?oaRequestId=${workflowRequestId}`, 'post').then(res => {
        this.loading = false;
        if (res.retStatus !== '1') { return false }
        window.open(res.retData);
      }).catch(() => {
        this.loading = false;
      });
    },
    /* 产品需求-跳转打开新页面 */
    openNewWindowPageFn (data) {
      const { href } = this.$router.resolve(data);
      window.open(href, '_blank');
    }
  }
};
</script>
<style lang="less" scoped>
.i-table-no-border .ivu-table-header th {
  background: #f8f8f8;
}
</style>
